<template>
  <div>
    <n-card :bordered="false" class="proCard table">
      <n-breadcrumb>
        <n-breadcrumb-item v-for="item in breadcrumb">
          {{ item }}
        </n-breadcrumb-item>
      </n-breadcrumb>
    </n-card>
    <n-grid class="mt-4" cols="1 s:1 m:4 l:4 xl:4 2xl:4" responsive="screen" :x-gap="12" :y-gap="8">
      <n-gi span="1">
        <n-card title="选择科室" :bordered="false" size="small" :segmented="{ content: true }">
          <template #header-extra>
            <n-button type="info" ghost icon-placement="left" @click="packHandle">
              全部{{ expandedKeys.length ? '收起' : '展开' }}
              <template #icon>
                <div class="flex items-center">
                  <n-icon size="14">
                    <AlignLeftOutlined />
                  </n-icon>
                </div>
              </template>
            </n-button>
          </template>
          <div class="w-full menu">
            <n-input type="input" v-model:value="pattern" placeholder="输入菜单名称搜索">
              <template #suffix>
                <n-icon size="18" class="cursor-pointer">
                  <SearchOutlined />
                </n-icon>
              </template>
            </n-input>
            <div class="py-3 menu-list">
              <template v-if="loading">
                <div class="flex items-center justify-center py-4">
                  <n-spin size="medium" />
                </div>
              </template>
              <template v-else>
                <n-tree
                  block-line 
                  cascade
                  key-field="depcode"
                  label-field="depname"
                  :pattern="pattern"
                  :virtual-scroll="true"
                  :expand-on-click="true"
                  :data="deptTreeData"
                  :expandedKeys="expandedKeys"
                  :selected-keys="selectedKeys"
                  @update:selected-keys="selectedTree"
                  @update:expanded-keys="onExpandedKeys"
                  style="height: calc(100vh - 336px)"
                />
              </template>
            </div>
          </div>
        </n-card>
      </n-gi>
      <n-gi span="3">
        <n-card :bordered="false">
          <template v-if="scheduleGroups.length == 0">
            <n-empty description="无排班数据" />
          </template>
          <template v-else>
            <n-grid cols="3 500:4 600:5" :y-gap="8" :x-gap="12">
              <n-gi v-for="(item, index) in scheduleGroups">
                <n-tag
                  class="scheduleTag"
                  :class="index == activeSchduleIndex ? '' : 'scheduleTagHover'"
                  :type="index == activeSchduleIndex ? 'success': ''"
                  @click="schduleChecked(item.workDate, index)"  
                >
                  <div style="margin-bottom: 10px;">
                    {{ item.workDate }} {{ item.dayOfWeek }}
                  </div>
                  {{ item.availableNumber }} / {{ item.reservedNumber }}
                </n-tag>
              </n-gi>
            </n-grid>
            <n-pagination 
              style="margin-top: 12px;" 
              v-model:page="pagination.current" 
              :page-count="pagination.pages"
              @update-page="onUpdatePage"
            />
          </template>
        </n-card>
        <n-card class="mt-4" :bordered="false">
          <n-data-table
            :columns="scheduleTableColumn"
            :data="scheduleTableData"
            :bordered="false"
          />
        </n-card>
      </n-gi>
    </n-grid>
  </div>
</template>
<script setup>
import { getDeptListTree } from '@/api/department'
import { getScheduleGruops, getScheduleList } from '@/api/schedule'
import { onMounted, reactive, ref, unref, watch, watchEffect } from 'vue';
import { useRoute } from 'vue-router';
import { scheduleTableColumn } from './columns'
import { AlignLeftOutlined, SearchOutlined } from '@vicons/antd'

let hosname = ''
let depname = ''
const route = useRoute()
const deptTreeData = ref([])
const scheduleGroups = ref([])
const scheduleTableData = ref([])
const pattern = ref('');
const breadcrumb = ref(['查看排班信息'])
const activeSchduleIndex = ref(0)
const groupParams = reactive({
  hoscode: '',
  depcode: ''
})


const pagination = reactive({
  current: 1,
  pages: 1,
  size: 5
})

let expandedKeys = ref([]);
let selectedKeys = ref([])

onMounted(() => {
  // 获取参数
  groupParams.hoscode = route.params.hoscode
  hosname = route.query.hosname
  // 设置面包屑第一个元素
  breadcrumb.value[0] = hosname
  fetchDeptList()
})

watch(activeSchduleIndex, (newData, oldData) => {
  fetchScheduleList()
})

const fetchDeptList = async () => {
  try {
    deptTreeData.value = await getDeptListTree(groupParams.hoscode)
    // 获取第一个科室的排班信息
    if (deptTreeData.value.length > 0) {
      const firstChild = deptTreeData.value[0].children[0]
      groupParams.depcode = firstChild.depcode
      depname = firstChild.depname
      expandedKeys.value = [deptTreeData.value[0].depcode]
      selectedKeys.value = [firstChild.depcode]
      fetchScheduleGruops()
    }
  } catch (error) {
    console.log(error)
  }
}

const fetchScheduleGruops = async () => {
  try {
    // 设置面包屑第二个值
    breadcrumb.value[1] = depname
    // 请求获取排班分组数据
    const pageData = await getScheduleGruops({...groupParams, ...pagination})
    scheduleGroups.value = pageData.records
    const { total, current, size, pages } = pageData
    Object.assign(pagination, { total, current, size, pages })
    // 获取默认第一个组的排班数据
    fetchScheduleList()
  } catch (error) {
    console.log(error);
  }
}

const fetchScheduleList = async () => {
  try {
    if (scheduleGroups.value.length == 0) {
      // 没有排班组数据, 清空排班数据，清除面包屑
      scheduleTableData.value = []
      breadcrumb.value.splice(2, 1)
      return
    }
    const workDateParam = scheduleGroups.value[activeSchduleIndex.value].workDate
    // 设置面包屑第三个值
    breadcrumb.value[2] = workDateParam
    scheduleTableData.value = await getScheduleList({ ...groupParams, workDate: workDateParam })
  } catch (error) {
    console.log(error);
  }
}

function packHandle() {
  if (expandedKeys.value.length) {
    expandedKeys.value = []
  } else {
    expandedKeys.value = unref(deptTreeData).map((item) => item.depcode)
  }
}

function selectedTree(keys, options, meta) {
  selectedKeys.value = keys
  const data = unref(options[0])
  if (meta.action === 'select' && !data.children && groupParams.depcode != data.depcode) {
    groupParams.depcode = data.depcode
    depname = data.depname
    // 获取选择科室的排班信息
    fetchScheduleGruops()
  }
}

function onExpandedKeys(keys) {
  expandedKeys.value = keys;
}

const schduleChecked = (workDate, index) => {
  if (index == activeSchduleIndex.value) return;
  activeSchduleIndex.value = index
}

function onUpdatePage() {
  fetchScheduleGruops()
}

</script>
<style scoped lang="less">
.py-3 {
  padding-top: .75rem;
  padding-bottom: .75rem;
}
.mt-4 {
  margin-top: 1rem;
}
.scheduleTag {
  height: 60px;
  cursor: pointer;
  border-radius: 8px;
  padding: 10px 12px;
  &.scheduleTagHover:hover {
    color: rgb(51, 54, 57);
    background-color: #eee;
  }
}

</style>